import React, { useEffect, useRef, useState, useMemo } from 'react';
import { Layout, Table, Pagination, Button, Row, Col, notification } from 'antd'
import { useParams } from 'react-router';
import {
    getFoods,
    deleteFood,
    getResturantDetail,
    getMenuById
} from 'src/api/getData'
import UploadModal from './UploadModal'
import './index.less'
import { cloneDeep } from 'lodash-es';

const { Content } = Layout;

function FoodList() {


    const { restaurant_id } = useParams()
    const [visible, setVisible] = useState(false);
    const [info, setInfo] = useState(null);

    // 搜索条件
    const [gettingQuery, setgettingQuery] = useState({
        pageNumber: 1,
        pageSize: 10,
    })

    const [loading, setLoading] = useState(false);
    const [state, setState] = useState({});

    const tableRef = useRef(null);

    // 表格行
    const columns = useMemo(() => ([
        {
            title: '食品名称',
            dataIndex: 'name'
        },
        {
            title: '食品介绍',
            dataIndex: 'description',
        },
        {
            title: '评分',
            dataIndex: 'rating',
        },
        {
            title: '操作',
            dataIndex: 'registe_time',
            render(text, record, index) {
                return <div>
                    <Button onClick={() => clickUpdteBtn(record)}>编辑</Button>
                    <Button onClick={() => deleteAsync(record)} type="primary" danger>删除</Button>
                </div>
            }
        },
    ]), []);

    // 初始化食物列表
    useEffect(() => {
        getFoodsAsync()
    }, [])

    // 获取美食列表
    async function getFoodsAsync(params = {}) {
        setLoading(true);
        const payload = {
            ...gettingQuery,
            ...params
        }
        setgettingQuery(payload)
        try {
            const res = await getFoods({ ...payload, restaurant_id });
            setState(res.data)
        } catch (err) {
            console.log('获取数据失败', err);
        }
        setLoading(false)
    }

    const handlePaginationChange = (page, pageSize) => {
        getFoodsAsync({
            pageNumber: pageSize !== gettingQuery.pageSize ? 1 : page,
            pageSize,
        })
    }


    // 点击编辑按钮
    function clickUpdteBtn(record) {
        setVisible(true)
        setInfo(record)
    }

    // 删除食品
    async function deleteAsync(record) {
        try {
            setLoading(true)
            const res = await deleteFood(record.id)
            setLoading(false)
            if (res.code === 0) {
                notification.success({
                    message: res.message
                })
            }
        } catch (error) {

        }
    }

    // 表格行展开
    const expandable = useMemo(() => {
        return {
            expandedRowRender(record) {
                return <Row gutter={[16, 24]}>
                    <Col className="gutter-row" span={12}>
                        <span>食品名称：</span>
                        <span>{record.name}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>餐馆名称：</span>
                        <span>{record.restaurant_name}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>食品 ID：</span>
                        <span>{record.item_id}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>餐馆 ID：</span>
                        <span>{record.restaurant_id}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>食品介绍：</span>
                        <span>{record.description}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>餐馆地址：</span>
                        <span>{record.restaurant_address}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>食品评分：</span>
                        <span>{record.rating}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>食品分类：</span>
                        <span>{record.category_name}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>月销量：</span>
                        <span>{record.month_sales}</span>
                    </Col>
                </Row>
            },
            onExpand(expanded, record) {
                if (expanded) {
                    // 获取
                    getResturantDetailAsync(record)
                    getMenuByIdAsync(record)
                }
                console.log(expanded, record, 'expandedRows')
            }
        }
    }, [state.list])


    // 获取餐厅信息
    async function getResturantDetailAsync(record) {
        try {

            const { restaurant_id } = record
            const res = await getResturantDetail(restaurant_id);
            const listNew = cloneDeep(state.list)
            const index = listNew.findIndex(item => item.item_id === record.item_id)
            listNew[index].restaurant_name = res.data.name
            listNew[index].restaurant_address = res.data.address
            setState({
                ...state,
                list: listNew
            })
        } catch (error) {
            console.error(error)
        }
    }


    // 获取分类信息
    async function getMenuByIdAsync(record) {
        try {

            const { category_id } = record
            const res = await getMenuById(category_id)
            const listNew = cloneDeep(state.list)
            const index = listNew.findIndex(item => item.item_id === record.item_id)
            listNew[index].category_name = res.data.name
            setState({
                ...state,
                list: listNew
            })
        } catch (error) {
            console.error(error)
        }
    }

    return <Layout className="shop-list-container">

        <Content>
            <div ref={tableRef} >
                <Table
                    rowKey="item_id"
                    columns={columns}
                    expandable={expandable}
                    dataSource={state.list || []}
                    bordered={true}
                    loading={loading}
                    pagination={false}
                    scroll={{
                        x: '100%',
                        y: 300
                    }}
                />
            </div>
            <Pagination
                pageSizeOptions={[10, 20, 30, 50]}
                showSizeChanger={true}
                onShowSizeChange={handlePaginationChange}
                onChange={handlePaginationChange}
                showTotal={total => `共${total}条`}
                className="ant-table-pagination ant-table-pagination-right"
                showQuickJumper={{
                    goButton: <Button
                        style={{ marginLeft: 8 }}
                    >跳转</Button>
                }}
                current={gettingQuery.pageNumber}
                pageSize={gettingQuery.pageSize}
                total={state.total}
            />
        </Content>
        {
            visible && <UploadModal
                visible={visible}
                info={info}
                onOk={function () {
                    setVisible(false)
                    setInfo(null)
                    getFoodsAsync()
                }}
                onCancel={function () {
                    setVisible(false)
                    setInfo(null)

                }}
            />
        }
    </Layout>
}

export default FoodList